﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using HM.UI.HMService;
using GalaSoft.MvvmLight.Command;
using System.Windows;

namespace HM.UI.Converters
{
    class ExpensesReportViewModel : INotifyPropertyChanged
    {
        private HMServiceClient proxy = new HMServiceClient();

        #region Ctors
        // Ctor for all expenses
        public ExpensesReportViewModel()
        {
            this.RefreshExpenses();
        }

        // Ctor for expenses filtered by date range
        public ExpensesReportViewModel(DateTime? from, DateTime? to)
        {
            this.RefreshExpensesByDateRange(from, to);
        } 
        #endregion

        #region Refresh
        private void RefreshExpenses()
        {
            this.proxy.GetExpensesCompleted += (s, e) =>
            {
                this.Expenses = e.Result;
            };

            this.proxy.GetExpensesAsync();
        }

        private void RefreshExpensesByDateRange(DateTime? from, DateTime? to)
        {
            this.proxy.GetExpensesByDateRangeCompleted += (s, e) =>
            {
                this.Expenses = e.Result;
            };

            this.proxy.GetExpensesByDateRangeAsync(from, to.Value.AddDays(1).AddSeconds(-1));
            // This is the trick I used to fix a bug: the same date in 'from' and 'to' parameters didn't return any result
            // (although records from that same date were present in the DB),
            // because it compares both date and time, and time that comes from datepicker is midnight.
            // Here I send midnight of the 'from' parameter and the last second of the day in 'to' parameter.
        }
        #endregion

        #region Properties

        private IEnumerable<Expense> expenses;
        public IEnumerable<Expense> Expenses
        {
            get
            {
                return this.expenses;
            }

            set
            {
                this.expenses = value;
                OnPropertyChanged("Expenses");
            }
        }

        #endregion

        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
